package cn.example.servlet;

import cn.educate.model.Video;
import cn.educate.service.VideoService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/getRandomVideos")
public class RandomVideosServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        VideoService videoService = new VideoService();
        List<Video> videos = videoService.getRandomVideos(20);

        // 设置响应内容类型为JSON
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 使用Gson将视频列表转换为JSON字符串
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(videos);

        // 将JSON字符串写入响应
        response.getWriter().write(json);
    }
}
